<template>
  <div>
    <el-container>
      <el-header>
        <div class="flex">
          <div class="margin-left-sm">
            <el-button
              type="primary"
              size="small"
              icon="el-icon-back"
              @click="backHome"
            >返回主页</el-button>
          </div>
          <div style="margin-left:10px;">
            档案详情
          </div>
        </div>
      </el-header>

      <el-container>
        <el-aside width="300px">
          <div
            class="flex"
            style="margin:15px 5px 0px 5px;"
          >
            <el-input
              v-model="filterText"
              placeholder="档案名称"
              class="filter-item"
              size="small"
            />
            <el-button
              v-if="addBtnShow"
              style="margin-left:10px;"
              type="primary"
              size="small"
              @click="handleNew"
            >新增</el-button>
          </div>
          <el-divider />
          <el-main style="height: calc(100vh - 290px);">
            <el-tree
              ref="treeRef"
              :highlight-current="true"
              :data="treedata"
              :props="defaultProps"
              node-key="Id"
              default-expand-all
              :filter-node-method="filterNode"
              :expand-on-click-node="false"
              @node-click="handleNodeClick"
            >
              <span
                slot-scope="{ node, data }"
                class="custom-tree-node"
              >
                <span>{{ node.label }}</span>
                <span v-if="!data.IsUse">(已停用)</span>
                <span v-else>
                  <el-button
                    type="text"
                    size="mini"
                    @click.stop="handleAddLeaf(node,data)"
                  >
                    <i class="el-icon-plus" />
                  </el-button>
                </span>
              </span>
            </el-tree>
          </el-main>

          <el-footer>
            <div>
              显示停用&nbsp;
              <el-switch
                v-model="queryList.IsUse"
                @change="switchChange"
              />
            </div>
            <el-dropdown
              trigger="click"
              @command="handleCommand"
            >
              <span class="el-dropdown-link">
                <i class="el-icon-s-operation" />更多操作
              </span>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item command="b">
                  <i class="el-icon-circle-plus" />下载模板
                </el-dropdown-item>
                <el-dropdown-item command="a">
                  <el-upload
                    ref="upload"
                    :data="queryList"
                    :on-success="uploadSuccess"
                    :on-error="uploadError"
                    :action="uploadurl"
                    :headers="uploadheaders"
                    :file-list="fileList"
                    :multiple="false"
                    list-type="text"
                    :limit="1"
                    :show-file-list="false"
                    accept=".xls,.xlsx"
                  >
                    <i class="el-icon-circle-plus" /> 导入数据
                  </el-upload>
                </el-dropdown-item>

                <el-dropdown-item command="c">
                  <i class="el-icon-circle-plus" />导出
                </el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </el-footer>
        </el-aside>
        <el-container>
          <el-main class="main-full-height  bg-white">
            <div style="margin:15px 0px 0px 10px;">编辑</div>
            <el-divider />
            <HelpTips
              v-if="!formIsShow"
              :page-name="'fileDetails'"
            />
            <el-form
              v-if="formIsShow"
              ref="dataForm"
              :rules="rules"
              :model="temp"
              label-width="80px"
              style="margin-left:30px;"
            >
              <el-row>
                <el-col :span="12">
                  <el-form-item
                    label="档案编号"
                    prop="ArchivesCode"
                  >
                    <el-input
                      v-model="temp.ArchivesCode"
                      :disabled="!btnIsShow"
                    />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="12">
                  <el-form-item
                    label="档案名称"
                    prop="ArchivesName"
                  >
                    <el-input
                      v-model="temp.ArchivesName"
                      :disabled="!btnIsShow"
                    />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="12">
                  <el-form-item label="所属上级">
                    <!-- 下拉树 -->
                    <SelectTree
                      ref="selecttreeref"
                      :props="fileProps"
                      :options="optionData"
                      :value="valueId"
                      :clearable="isClearable"
                      :accordion="isAccordion"
                      :is-disabled="!btnIsShow"
                      @getValue="getProjectValue($event)"
                    />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-divider />
              <el-form-item label="是否启用">
                <el-switch
                  v-model="temp.IsUse"
                  :disabled="!btnIsShow"
                />
              </el-form-item>
              <el-form-item label="可见范围">
                <el-radio-group
                  v-model="temp.IsPartUse"
                  :disabled="!btnIsShow"
                >
                  <el-radio :label="1">全部可见</el-radio>
                  <el-radio :label="2">部分可见</el-radio>
                </el-radio-group>
                <div v-if="temp.IsPartUse == 2">
                  <el-button
                    v-if="temp.IsPartUse == 2"
                    type="primary"
                    size="mini"
                    plain
                    @click="openChoice"
                  >
                    选择可见范围</el-button>
                  <div class="select-person">
                    <el-row
                      type="flex"
                      style="flex-wrap: wrap;"
                    >
                      <el-tag
                        v-for="tag in addtags"
                        :key="tag.Id"
                        closable
                        :type="
                          tag.Type === 1
                            ? tagType.warning
                            : tag.Type === 2
                              ? tagType.success
                              : tagType.danger
                        "
                        style="margin: 10px"
                        @close="handleClose(tag)"
                      >
                        {{ tag.Name }}
                      </el-tag>
                    </el-row>
                  </div>
                </div>
              </el-form-item>
            </el-form>
          </el-main>
          <el-footer>
            <div v-if="btnIsShow">
              <el-button
                type="primary"
                size="small"
                style="width:100px"
                @click="createData()"
              >保存</el-button>
            </div>
          </el-footer>
        </el-container>
      </el-container>
    </el-container>
    <selectAllInOne
      ref="selectallinonedialog"
      :echo-list="addtags"
      @allSelect="allSelect"
    />
  </div>
</template>
<script>
import fileDownload from 'js-file-download'
import HelpTips from '@/views/components/common/helptips/help'
import axios from 'axios'
import { config } from '@/utils/requestconfig'
import { getToken } from '@/utils/auth' // 获取token
import SelectTree from '@/components/selecttree/selecttree'
import selectAllInOne from '@/views/components/permissions/selectpersonroledepartment'
import {
  getListAndTree,
  saveData,
  getCount
} from '@/api/customarchives/customarchivesdetail'
import { getById } from '@/api/customarchives/customarchives'
export default {
  components: { selectAllInOne, SelectTree, HelpTips },
  data() {
    return {
      filterText: '',
      /** *************上传**************** */
      fileList: [],
      uploadurl:
        config.webapi + 'SysCustomArchivesDetail/UploadingStream',
      uploadheaders: {
        Authorization: getToken(),
        ContentType: 'application/json'
      },
      uploaddata: { dir: 'uploadFile' },
      /** 选择树 */
      isClearable: false, // 可清空（可选）
      isAccordion: true, // 可收起（可选）
      optionData: [],
      valueId: '',
      fileProps: {
        // 配置项（必选）
        value: 'Id',
        label: 'name',
        children: 'Children'
      },
      /** ********************************* 权限 *************************************************/
      tagType: { success: 'success', warning: 'warning', danger: 'danger' }, // tag显示类型
      addtags: [],
      /** ****************************form*************************************** */
      // 新增分组表单
      formIsShow: false,
      btnIsShow: false,
      addBtnShow: false,
      temp: {
        Id: '',
        ArchivesId: '', // 档案分类ID
        ArchivesCode: '', // 档案编号
        ArchivesName: '', // 档案名称
        ArchivesRange: '', // 可见范围
        ParentId: '', // 上级档案Id
        IsUse: true, // 是否启用   1 启用 2 不启用
        IsPartUse: 1 // 是否全部可见 1 全部 2部分
      },
      // 验证规则
      rules: {
        ArchivesName: [
          { required: true, message: '档案名称必填', trigger: 'blur' }
        ],
        ArchivesCode: [
          { required: true, message: '档案编码必填', trigger: 'blur' }
        ]
      },
      /** *****************左边树************** */
      treedata: [],
      defaultProps: {
        Id: 'Id',
        children: 'Children',
        label: 'name'
      },
      saveBackId: '',
      // 查询参数
      queryList: {
        SearchKey: '',
        ArchivesId: '',
        IsUse: false,
        LeveId: ''
      },
      outList: {
        SearchKey: '',
        ArchivesId: '',
        IsUse: true,
        LeveId: ''
      },
      putList: {
        SearchKey: '',
        ArchivesId: '',
        IsUse: true,
        LeveId: ''
      }
    }
  },
  watch: {
    filterText(val) {
      this.$refs.treeRef.filter(val)
    }
  },
  mounted() {
    this.getData()
  },
  methods: {
    filterNode(value, data) {
      if (!value) return true
      return data.name.indexOf(value) !== -1
    },
    backHome() {
      this.$router.push({
        path: '/baseconfig/customarchives/index/',
        name: '自定义档案'
      })
    },
    handleClose(tag) {
      this.addtags.splice(this.addtags.indexOf(tag), 1)
    },
    switchChange() {
      this.queryList.LeveId = ''
      this.getData()
      this.formIsShow = false
      this.btnIsShow = false
      this.addBtnShow = false
    },
    handleAddLeaf(node, data) {
      this.formIsShow = true
      this.btnIsShow = true
      this.init()
      this.queryList.ArchivesId = this.$route.params.Id
      var _this = this
      this.queryList.LeveId = ''
      this.queryList.IsUse = false
      getListAndTree(_this.queryList).then(res => {
        _this.optionData = res.Data
        this.$nextTick(() => {
          // 初始化权限选择和所属上级
          this.valueId = data.Id
          this.temp.ParentId = this.valueId
          this.addtags = []
        })
      })
      // 生成编码
      var fatherId = ''
      getById(this.$route.params.Id).then(res => {
        fatherId = res.Data.ArchivesCode
        getCount(this.$route.params.Id).then(res => {
          this.temp.ArchivesCode = fatherId + '-' + res.Data
        })
      })
    },
    handleNew() {
      this.formIsShow = true
      this.btnIsShow = true
      this.init()
      this.queryList.ArchivesId = this.$route.params.Id
      var fatherNodeId = this.queryList.LeveId
      var _this = this
      this.queryList.LeveId = ''
      getListAndTree(_this.queryList).then(res => {
        _this.optionData = res.Data
        this.$nextTick(() => {
          _this.valueId = fatherNodeId
          _this.temp.ParentId = fatherNodeId
        })
      })
      // 生成编码
      var fatherId = ''
      getById(this.$route.params.Id).then(res => {
        fatherId = res.Data.ArchivesCode
        getCount(this.$route.params.Id).then(res => {
          this.temp.ArchivesCode = fatherId + '-' + res.Data
        })
      })
      // 初始化权限选择和所属上级

      this.addtags = []
    },
    handleCommand(command) {
      var _this = this
      // 导入
      if (command === 'a') {
        this.putList.ArchivesId = this.$route.params.Id
      }
      // 导出模板
      if (command === 'b') {
        axios({
          method: 'POST',
          url:
            config.webapi +
            'SysCustomArchivesDetail/DownExcelStreamEntity',
          headers: { Authorization: getToken() },
          responseType: 'arraybuffer'
        }).then(res => {
          fileDownload(res.data, '档案明细模板.xls') // 调用文件流解析插件生成excel
        })
      }
      // 导出
      if (command === 'c') {
        _this.outList.IsUse = false
        _this.outList.ArchivesId = this.$route.params.Id
        var name = '档案明细.xls'
        this.$confirm('确认是否导出数据?', '提示', {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(() => {
            axios({
              method: 'POST',
              url:
                config.webapi + 'SysCustomArchivesDetail/DownExcelStream',
              headers: { Authorization: getToken() },
              responseType: 'arraybuffer',
              data: _this.outList
            }).then(res => {
              fileDownload(res.data, name) // 调用文件流解析插件生成excel
            })
          })
          .catch(() => {
            this.$message({
              type: 'info',
              message: '已取消导出'
            })
          })
      }
    },
    init() {
      this.temp = {
        Id: '',
        ArchivesId: '',
        ArchivesCode: '',
        ArchivesName: '',
        ArchivesRange: '',
        ParentId: '',
        IsUse: true,
        IsPartUse: 1
      }
    },
    getData() {
      this.queryList.ArchivesId = this.$route.params.Id
      var _this = this
      getListAndTree(_this.queryList).then(res => {
        _this.treedata = res.Data
        this.$nextTick(() => {
          if (
            _this.saveBackId === '' ||
            _this.saveBackId === null ||
            _this.saveBackId === undefined
          ) {
            return
          } else {
            this.$refs.treeRef.setCurrentKey(_this.saveBackId)
            var arr = res.Extend.filter(x => x.Id === _this.saveBackId)
            _this.formIsShow = true
            var backData = {
              Id: arr[0].Id,
              ArchivesId: arr[0].ArchivesId,
              ArchivesCode: arr[0].ArchivesCode,
              ArchivesName: arr[0].ArchivesName,
              ArchivesRange: arr[0].ArchivesRange,
              ParentId: arr[0].ParentId,
              IsUse: arr[0].IsUse,
              IsPartUse: arr[0].IsPartUse
            }
            _this.handleNodeClick(backData)
          }
        })
      })
    },
    createData() {
      var _this = this
      this.temp.ArchivesId = this.$route.params.Id
      if (this.temp.IsPartUse === 2) {
        this.temp.ArchivesRange = JSON.stringify(this.addtags)
      }
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          saveData(_this.temp).then(res => {
            // _this.init()
            this.$message({
              type: 'success',
              message: res.Msg
            })
            _this.saveBackId = res.Data
            _this.queryList.LeveId = ''
            _this.getData()
          })
        }
      })
    },
    handleFilter() {
      this.queryList.LeveId = ''
      this.getData()
    },
    // 点击树形节点
    handleNodeClick(data) {
      var _this = this
      if (data.ParentId) {
        this.formIsShow = true
        this.btnIsShow = true
      } else {
        this.btnIsShow = false
        this.formIsShow = true
      }
      this.addBtnShow = true
      // 分类id
      this.queryList.ArchivesId = this.$route.params.Id
      // 点击的节点id
      this.queryList.LeveId = data.Id
      // 获取树形节点
      getListAndTree(_this.queryList).then(res => {
        _this.optionData = res.Data
        this.$nextTick(() => {
          this.valueId = data.ParentId
        })
      })
      this.temp = Object.assign(data, {})
      if (data.ArchivesRange !== '') {
        this.addtags = JSON.parse(data.ArchivesRange)
      }
    },
    /** **************** 权限***************** */
    openChoice() {
      this.$refs.selectallinonedialog.showSelectAllInOneDialog()
    },
    // 回调方法
    allSelect(taglist) {
      this.addtags = taglist
    },
    /** ********************* 树形选择 *************/
    // 选择分组
    getProjectValue(value) {
      this.valueId = value
      this.temp.ParentId = this.valueId || ''
    },
    /** *****************上传*********************** */
    uploadError(err) {
      this.$message({
        type: 'error',
        message: '上传失败'
      })
      console.log(err)
    },
    uploadSuccess(respons) {
      if (respons.Code === 0) {
        this.$message({
          type: 'error',
          message: respons.Msg
        })
      } else {
        this.$message({
          type: 'success',
          message: respons.Msg
        })
        this.$refs.upload.clearFiles()
        this.saveBackId = ''
        this.queryList.LeveId = ''
        this.getData()
      }
    }
  }
}
</script>
<style scoped>
.el-dropdown-link {
  cursor: pointer;
  color: #409eff;
}
</style>
